package br.com.travesso.security.exception;

import javax.security.jacc.PolicyContext;
import javax.servlet.http.HttpServletRequest;

import br.gov.component.demoiselle.security.auth.AuthException;
import br.gov.component.demoiselle.security.auth.message.implementation.RequestThrowableHandler;

public class SecurityRequestThrowableHandler extends RequestThrowableHandler {

	private static final String THROWABLE_KEY = "javax.servlet.error.exception";

	@Override
	public void handle(Throwable throwable) {
		colocarExcecaoNoRequest(throwable);
	}

	private static void colocarExcecaoNoRequest(Throwable t) {
		obterRequest().setAttribute(THROWABLE_KEY, t);
	}

	public static Throwable retirarExcecaoDoRequest() {
		Throwable e = (Throwable) obterRequest().getAttribute(THROWABLE_KEY);
		obterRequest().removeAttribute(
				SecurityRequestThrowableHandler.THROWABLE_KEY);
		return e;
	}

	private static HttpServletRequest obterRequest() {
		try {
			HttpServletRequest request = (HttpServletRequest) PolicyContext
					.getContext(HttpServletRequest.class.getName());
			return request;
		} catch (Exception e) {
			throw new AuthException("Error: Could not get context "
					+ HttpServletRequest.class.getName() + " in PolicyContext",
					e);
		}
	}

}
